<template>
  <div class="api-test-page">
    <div class="header">
      <h1>API接口测试页面</h1>
      <p class="subtitle">验证所有API接口的可访问性（无需认证）</p>
      
      <div class="test-actions">
        <el-button 
          type="primary" 
          size="large" 
          :loading="globalTesting"
          @click="runAllTests"
        >
          <el-icon><Refresh /></el-icon>
          运行所有测试
        </el-button>
        
        <el-button 
          type="success" 
          size="large" 
          :loading="autoTesting"
          @click="runAutomatedTests"
        >
          <el-icon><Check /></el-icon>
          自动化测试
        </el-button>
        
        <el-button 
          type="info" 
          size="large" 
          @click="clearResults"
        >
          清除结果
        </el-button>
      </div>
    </div>

    <div class="test-sections">
      <!-- 健康分析API测试 -->
      <div class="test-section">
        <h2>健康分析API测试</h2>
        <div class="test-buttons">
          <el-button @click="testHealthAnalysis" type="primary">生成健康分析</el-button>
          <el-button @click="testVitalSigns" type="primary">生命体征分析</el-button>
          <el-button @click="testHealthTrends" type="primary">健康趋势分析</el-button>
          <el-button @click="testRiskAssessment" type="primary">风险评估</el-button>
          <el-button @click="testSymptomPatterns" type="primary">症状模式分析</el-button>
          <el-button @click="testAnalysisRecords" type="success">获取分析记录</el-button>
        </div>
        <div class="test-results">
          <h3>健康分析测试结果：</h3>
          <pre>{{ healthAnalysisResults }}</pre>
        </div>
      </div>

      <!-- 通知API测试 -->
      <div class="test-section">
        <h2>通知API测试</h2>
        <div class="test-buttons">
          <el-button @click="testCreateNotification" type="primary">创建系统通知</el-button>
          <el-button @click="testCreateAppointmentNotification" type="primary">创建预约通知</el-button>
          <el-button @click="testCreateHealthReminder" type="primary">创建健康提醒</el-button>
          <el-button @click="testGetUserNotifications" type="success">获取用户通知</el-button>
          <el-button @click="testGetRecentNotifications" type="success">获取最近通知</el-button>
        </div>
        <div class="test-results">
          <h3>通知测试结果：</h3>
          <pre>{{ notificationResults }}</pre>
        </div>
      </div>

      <!-- 预约API测试 -->
      <div class="test-section">
        <h2>预约API测试</h2>
        <div class="test-buttons">
          <el-button @click="testCreateAppointment" type="primary">创建预约</el-button>
          <el-button @click="testGetMyAppointments" type="success">获取我的预约</el-button>
          <el-button @click="testGetAvailableSlots" type="success">获取可用时段</el-button>
        </div>
        <div class="test-results">
          <h3>预约测试结果：</h3>
          <pre>{{ appointmentResults }}</pre>
        </div>
      </div>

      <!-- 健康记录API测试 -->
      <div class="test-section">
        <h2>健康记录API测试</h2>
        <div class="test-buttons">
          <el-button @click="testGetHealthRecord" type="success">获取健康档案</el-button>
          <el-button @click="testUpdateHealthRecord" type="primary">更新健康档案</el-button>
          <el-button @click="testAddVitalSigns" type="primary">添加生命体征</el-button>
        </div>
        <div class="test-results">
          <h3>健康记录测试结果：</h3>
          <pre>{{ healthRecordResults }}</pre>
        </div>
      </div>

      <!-- 用户API测试 -->
      <div class="test-section">
        <h2>用户API测试</h2>
        <div class="test-buttons">
          <el-button @click="testGetUserProfile" type="success">获取用户资料</el-button>
          <el-button @click="testUpdateUserProfile" type="primary">更新用户资料</el-button>
        </div>
        <div class="test-results">
          <h3>用户测试结果：</h3>
          <pre>{{ userResults }}</pre>
        </div>
      </div>

      <!-- 症状评估API测试 -->
      <div class="test-section">
        <h2>症状评估API测试</h2>
        <div class="test-buttons">
          <el-button @click="testSymptomAssessment" type="primary">症状评估</el-button>
          <el-button @click="testGetSymptomHistory" type="success">获取症状历史</el-button>
        </div>
        <div class="test-results">
          <h3>症状评估测试结果：</h3>
          <pre>{{ symptomResults }}</pre>
        </div>
      </div>

      <!-- 健康检查API测试 -->
      <div class="test-section">
        <h2>健康检查API测试</h2>
        <div class="test-buttons">
          <el-button @click="testDeepSeekHealth" type="primary">DeepSeek健康检查</el-button>
          <el-button @click="testApiKeyStatus" type="success">API密钥状态</el-button>
          <el-button @click="testSystemHealth" type="info">系统健康状态</el-button>
          <el-button @click="testQuickHealthCheck" type="warning">快速健康检查</el-button>
        </div>
        <div class="test-results">
          <h3>健康检查测试结果：</h3>
          <pre>{{ healthCheckResults }}</pre>
        </div>
      </div>
    </div>

    <!-- 全局测试结果 -->
    <div class="global-results">
      <h2>全局测试状态</h2>
      <div class="status-grid">
        <div class="status-item" :class="{ success: testStatus.healthAnalysis, error: testStatus.healthAnalysis === false }">
          <span>健康分析API</span>
          <span>{{ getStatusText(testStatus.healthAnalysis) }}</span>
        </div>
        <div class="status-item" :class="{ success: testStatus.notifications, error: testStatus.notifications === false }">
          <span>通知API</span>
          <span>{{ getStatusText(testStatus.notifications) }}</span>
        </div>
        <div class="status-item" :class="{ success: testStatus.appointments, error: testStatus.appointments === false }">
          <span>预约API</span>
          <span>{{ getStatusText(testStatus.appointments) }}</span>
        </div>
        <div class="status-item" :class="{ success: testStatus.healthRecords, error: testStatus.healthRecords === false }">
          <span>健康记录API</span>
          <span>{{ getStatusText(testStatus.healthRecords) }}</span>
        </div>
        <div class="status-item" :class="{ success: testStatus.user, error: testStatus.user === false }">
          <span>用户API</span>
          <span>{{ getStatusText(testStatus.user) }}</span>
        </div>
        <div class="status-item" :class="{ success: testStatus.symptoms, error: testStatus.symptoms === false }">
          <span>症状评估API</span>
          <span>{{ getStatusText(testStatus.symptoms) }}</span>
        </div>
        <div class="status-item" :class="{ success: testStatus.healthCheck, error: testStatus.healthCheck === false }">
          <span>健康检查API</span>
          <span>{{ getStatusText(testStatus.healthCheck) }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { api } from '../api/request'
import { healthCheckApi } from '../api/healthCheck'
import { functionTester } from '../utils/functionTest'
import { 
  Bell, 
  Calendar, 
  Document, 
  User, 
  ChatDotRound,
  Refresh,
  Check
} from '@element-plus/icons-vue'

// 测试结果数据
const healthAnalysisResults = ref('')
const notificationResults = ref('')
const appointmentResults = ref('')
const healthRecordResults = ref('')
const userResults = ref('')
const symptomResults = ref('')
const healthCheckResults = ref('')

// 测试状态
const testStatus = reactive({
  healthAnalysis: null,
  notifications: null,
  appointments: null,
  healthRecords: null,
  user: null,
  symptoms: null,
  healthCheck: null
})

// 全局测试状态
const globalTesting = ref(false)
const autoTesting = ref(false)

// 获取状态文本
const getStatusText = (status) => {
  if (status === null) return '未测试'
  return status ? '✅ 正常' : '❌ 失败'
}

// 通用API测试函数
const testApi = async (apiCall, resultRef, statusKey, description) => {
  try {
    resultRef.value = `正在测试 ${description}...`
    const result = await apiCall()
    resultRef.value = JSON.stringify(result, null, 2)
    testStatus[statusKey] = true
    ElMessage.success(`${description} 测试成功`)
  } catch (error) {
    resultRef.value = `错误: ${error.message}\n${JSON.stringify(error.response?.data || error, null, 2)}`
    testStatus[statusKey] = false
    ElMessage.error(`${description} 测试失败: ${error.message}`)
  }
}

// 健康分析API测试
const testHealthAnalysis = () => {
  testApi(
    () => api.post('/api/health-analytics/generate', {
      userId: 1,
      analysisType: 'COMPREHENSIVE',
      timeRange: '30days'
    }),
    healthAnalysisResults,
    'healthAnalysis',
    '生成健康分析'
  )
}

const testVitalSigns = () => {
  testApi(
    () => api.post('/api/health-analytics/vital-signs', {
      userId: 1,
      timeRange: '7days'
    }),
    healthAnalysisResults,
    'healthAnalysis',
    '生命体征分析'
  )
}

const testHealthTrends = () => {
  testApi(
    () => api.post('/api/health-analytics/trends', {
      userId: 1,
      metrics: ['weight', 'blood_pressure'],
      timeRange: '30days'
    }),
    healthAnalysisResults,
    'healthAnalysis',
    '健康趋势分析'
  )
}

const testRiskAssessment = () => {
  testApi(
    () => api.post('/api/health-analytics/risk-assessment', {
      userId: 1,
      riskFactors: ['age', 'weight', 'family_history']
    }),
    healthAnalysisResults,
    'healthAnalysis',
    '风险评估'
  )
}

const testSymptomPatterns = () => {
  testApi(
    () => api.post('/api/health-analytics/symptom-patterns', {
      userId: 1,
      timeRange: '90days'
    }),
    healthAnalysisResults,
    'healthAnalysis',
    '症状模式分析'
  )
}

const testAnalysisRecords = () => {
  testApi(
    () => api.get('/api/health-analytics/records', {
      userId: 1, page: 0, size: 10
    }),
    healthAnalysisResults,
    'healthAnalysis',
    '获取分析记录'
  )
}

// 通知API测试
const testCreateNotification = () => {
  testApi(
    () => api.post('/api/notifications/system', {
      title: '系统通知测试',
      content: '这是一个系统通知测试消息',
      priority: 'medium'
    }),
    notificationResults,
    'notifications',
    '创建系统通知'
  )
}

const testCreateAppointmentNotification = () => {
  testApi(
    () => api.post('/api/notifications/appointment', {
      appointmentId: 1,
      reminderTime: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
    }),
    notificationResults,
    'notifications',
    '创建预约通知'
  )
}

const testCreateHealthReminder = () => {
  testApi(
    () => api.post('/api/notifications/health-reminder', {
      reminderType: 'medication',
      content: '请记得按时服药',
      scheduledTime: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString()
    }),
    notificationResults,
    'notifications',
    '创建健康提醒'
  )
}

const testGetUserNotifications = () => {
  testApi(
    () => api.get('/api/notifications/user', {
      page: 0, size: 10
    }),
    notificationResults,
    'notifications',
    '获取用户通知'
  )
}

const testGetRecentNotifications = () => {
  testApi(
    () => api.get('/api/notifications/recent', {
      limit: 5
    }),
    notificationResults,
    'notifications',
    '获取最近通知'
  )
}

// 预约API测试
const testCreateAppointment = () => {
  testApi(
    () => api.post('/api/appointments', {
      doctorId: 1,
      appointmentDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      appointmentTime: '10:00',
      reason: 'API测试预约',
      notes: '这是一个测试预约'
    }),
    appointmentResults,
    'appointments',
    '创建预约'
  )
}

const testGetMyAppointments = () => {
  testApi(
    () => api.get('/api/appointments/my'),
    appointmentResults,
    'appointments',
    '获取我的预约'
  )
}

const testGetAvailableSlots = () => {
  testApi(
    () => api.get('/api/appointments/available-slots', {
      doctorId: 1,
      date: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
    }),
    appointmentResults,
    'appointments',
    '获取可用时段'
  )
}

// 健康记录API测试
const testGetHealthRecord = () => {
  testApi(
    () => api.get('/api/health/record'),
    healthRecordResults,
    'healthRecords',
    '获取健康档案'
  )
}

const testUpdateHealthRecord = () => {
  testApi(
    () => api.put('/api/health/record', {
      allergies: '无已知过敏',
      medicalHistory: '无重大疾病史',
      height: 170,
      weight: 65,
      bloodType: 'A'
    }),
    healthRecordResults,
    'healthRecords',
    '更新健康档案'
  )
}

const testAddVitalSigns = () => {
  testApi(
    () => api.post('/api/health/vital-signs', {
      bloodPressure: '120/80',
      heartRate: 72,
      temperature: 36.5,
      weight: 65,
      recordDate: new Date().toISOString()
    }),
    healthRecordResults,
    'healthRecords',
    '添加生命体征'
  )
}

// 用户API测试
const testGetUserProfile = () => {
  testApi(
    () => api.get('/api/user/profile'),
    userResults,
    'user',
    '获取用户资料'
  )
}

const testUpdateUserProfile = () => {
  testApi(
    () => api.put('/api/user/profile', {
      realName: '测试用户',
      phone: '13800138000',
      email: 'test@example.com'
    }),
    userResults,
    'user',
    '更新用户资料'
  )
}

// 症状评估API测试
const testSymptomAssessment = () => {
  testApi(
    () => api.post('/api/symptom/assess', {
      symptoms: ['头痛', '发热'],
      severity: 'moderate',
      duration: '2天'
    }),
    symptomResults,
    'symptoms',
    '症状评估'
  )
}

const testGetSymptomHistory = () => {
  testApi(
    () => api.get('/api/symptom/history', {
      page: 0, size: 10
    }),
    symptomResults,
    'symptoms',
    '获取症状历史'
  )
}

// 运行所有测试
const runAllTests = async () => {
  globalTesting.value = true
  try {
    // 重置所有状态
    Object.keys(testStatus).forEach(key => {
      testStatus[key] = null
    })
    
    // 依次运行所有测试
    await Promise.all([
      testHealthAnalysis(),
      testCreateNotification(),
      testCreateAppointment(),
      testGetHealthRecord(),
      testGetUserProfile(),
      testSymptomAssessment()
    ])
    
    ElMessage.success('所有测试完成')
  } catch (error) {
    ElMessage.error('测试过程中出现错误')
  } finally {
    globalTesting.value = false
  }
}


 
 // 获取症状历史（修复版本）
 const testGetSymptomHistoryFixed = async () => {
   try {
     const response = await api.get('/api/symptoms/history')
     symptomResults.value = JSON.stringify(response, null, 2)
     testStatus.symptoms = response.success ? 'success' : 'error'
   } catch (error) {
     symptomResults.value = `错误: ${error.message}`
     testStatus.symptoms = 'error'
   }
 }

// 健康检查API测试方法
const testDeepSeekHealth = () => {
  testApi(
    () => healthCheckApi.checkDeepSeekHealth(),
    healthCheckResults,
    'healthCheck',
    'DeepSeek健康检查'
  )
}

const testApiKeyStatus = () => {
  testApi(
    () => healthCheckApi.checkApiKeyStatus(),
    healthCheckResults,
    'healthCheck',
    'API密钥状态检查'
  )
}

const testSystemHealth = () => {
  testApi(
    () => healthCheckApi.checkSystemHealth(),
    healthCheckResults,
    'healthCheck',
    '系统健康状态检查'
  )
}

const testQuickHealthCheck = () => {
  testApi(
    () => healthCheckApi.quickHealthCheck(),
    healthCheckResults,
    'healthCheck',
    '快速健康检查'
  )
}
 
 // 自动化测试
 const runAutomatedTests = async () => {
   autoTesting.value = true
   try {
     // 清除之前的结果
     clearResults()
     
     // 按顺序运行关键测试
     const tests = [
       { fn: testGetUserProfile, name: '用户资料' },
       { fn: testGetHealthRecord, name: '健康档案' },
       { fn: testHealthAnalysis, name: '健康分析' },
       { fn: testGetMyAppointments, name: '预约查询' },
       { fn: testGetUserNotifications, name: '通知查询' },
       { fn: testGetSymptomHistoryFixed, name: '症状历史' },
       { fn: testDeepSeekHealth, name: 'DeepSeek健康检查' },
       { fn: testSystemHealth, name: '系统健康检查' }
     ]
     
     for (const test of tests) {
       await new Promise(resolve => setTimeout(resolve, 500)) // 延迟500ms
       await test.fn()
     }
     
     ElMessage.success('自动化测试完成')
   } catch (error) {
     ElMessage.error('自动化测试失败')
   } finally {
     autoTesting.value = false
   }
 }

// 清除所有结果
const clearResults = () => {
  healthAnalysisResults.value = ''
  notificationResults.value = ''
  appointmentResults.value = ''
  healthRecordResults.value = ''
  userResults.value = ''
  symptomResults.value = ''
  
  Object.keys(testStatus).forEach(key => {
    testStatus[key] = null
  })
  
  ElMessage.info('已清除所有测试结果')
}
</script>

<style scoped>
.api-test-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h1 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.subtitle {
  color: #7f8c8d;
  font-size: 16px;
}

.test-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 15px;
  flex-wrap: wrap;
}

.test-sections {
  display: grid;
  gap: 30px;
}

.test-section {
  border: 1px solid #e1e8ed;
  border-radius: 8px;
  padding: 20px;
  background: #fff;
}

.test-section h2 {
  color: #34495e;
  margin-bottom: 15px;
  border-bottom: 2px solid #3498db;
  padding-bottom: 5px;
}

.test-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.test-results {
  background: #f8f9fa;
  border-radius: 4px;
  padding: 15px;
}

.test-results h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #2c3e50;
}

.test-results pre {
  background: #2c3e50;
  color: #ecf0f1;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  max-height: 300px;
  font-size: 12px;
  line-height: 1.4;
}

.global-results {
  margin-top: 40px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.global-results h2 {
  color: #2c3e50;
  margin-bottom: 20px;
  text-align: center;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #fff;
  border-radius: 6px;
  border: 2px solid #e1e8ed;
  transition: all 0.3s ease;
}

.status-item.success {
  border-color: #27ae60;
  background: #d5f4e6;
}

.status-item.error {
  border-color: #e74c3c;
  background: #fdf2f2;
}

.status-item span:first-child {
  font-weight: 600;
  color: #2c3e50;
}

.status-item span:last-child {
  font-weight: 500;
}

@media (max-width: 768px) {
  .test-buttons {
    flex-direction: column;
  }
  
  .status-grid {
    grid-template-columns: 1fr;
  }
}
</style>